package Model;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import DBAccess.DBAccess;

import org.json.*;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private Properties props = new Properties();   
	
    @Override
	public
	void init() {
    	new DBAccess();
		InputStream in = this.getServletContext().getResourceAsStream("/config.properties");
		try {
			props.load(in);
		} catch(Exception e) {
			System.err.println("Unrecoverable error. Could not load configuration.");
			return;
		}
	} 
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String name = request.getParameter("name");
		String password = request.getParameter("password");
		request.setAttribute("tryingAgain", false);
		System.out.println("this is" + name + password);
		RequestDispatcher dispatcher;
		String referer = request.getHeader("Referer");
		System.out.println(referer);
		if (referer == null || referer.equals("http://localhost:8080/UBCDatingServer/login.jsp")){
			referer="http://localhost:8080/UBCDatingServer/index.jsp";
		}
		int valid = Login.login(name,password);
		System.out.println("Valid"+valid);
		if(valid >= 0)
		{
			HttpSession session = request.getSession();
			if(session != null) {
			session.setAttribute("loggedIn", true);
			session.setAttribute("userID", valid );
			User myU = new User(valid, true);
			JSONObject myJson = new JSONObject(myU);
			System.out.print(myJson);
			session.setAttribute("userInfo", myJson);
			session.setAttribute("name", myU.getName());
			
//				response.sendRedirect(referer);
				String originalTarget = (String) session.getAttribute("originalTarget");
				if(originalTarget != null) {

					response.sendRedirect(originalTarget);
					return;
				}
			}
//			dispatcher = request.getRequestDispatcher(referer);
			response.sendRedirect(referer);
			
		} else {
			request.setAttribute("tryingAgain", true);
//			dispatcher = request.getRequestDispatcher(referer);
			response.sendRedirect(referer);
		}
	}

}
